const lockDataUtil = require('./lockDataUtil')
const SerialPort = require('serialport')
//Opening a Port
let serialPort
//指令监听
const cmdList = {
  0x01: "开单箱",
  0x05: "全开箱",
  0x07: "正确应答",
  0x02: "错误应答",
  0x08: "获取全部探物",
  0x09: "获取全部锁态",
  0x0a: "获取单探物",
  0x0b: "获取单锁态",
  0x06: "获取全探物和锁态",
  0xaa: "全状态应答",
  0xab: "单状态应答",
  0x0d: "开灯",
  0x0e: "关灯",
  0x0f: "开单箱同时开灯",
}

function sendData(data) {
  if (!serialPort) throw new Error("串口未打卡")
  let arr = lockDataUtil.logic2Total(data)
  console.log("发送命令", arr.map(item => item.replace("0x", "")).join(" "))
  let buf = Buffer.from(arr)

  let re = serialPort.write(buf)
  if (!re) {
    throw new Error("消息发送失败")
  }
}

function open(path) {
  return new Promise((resolve, reject) => {
    serialPort = new SerialPort(path)
    serialPort.on("open", () => {
      console.log("打开")
      resolve()
    })
    let arr = []
    serialPort.on('data', function (data) {
      for (let i = 0; i < data.length; i++) {
        arr.push(data[i].toString(16))
        let endIdx = arr.indexOf("3")
        if (endIdx > -1 && endIdx + 3 === arr.length) {
          console.log("收到命令", arr.join(" "))
          let addr = lockDataUtil.convertAnsi([arr[2], arr[3]])
          let boxNum = lockDataUtil.convertAnsi([arr[4], arr[5]])
          let cmd = lockDataUtil.convertAnsi([arr[6], arr[7]])
          console.log("柜号", addr)
          console.log("箱号", boxNum)
          console.log("命令", cmd, cmdList[cmd])
          if (endIdx > 9) {
            let d = []
            let dataArr = arr.slice(9, endIdx)
            for (let j = 0; j < dataArr.length; j += 2) {
              d.push(lockDataUtil.convertAnsi([dataArr[j], dataArr[j + 1]]))
            }
            console.log("数据", d.map(item => item.toString(16)).join(" "))
          }
          arr = []
        }
      }
    })
    //错误监听
    serialPort.on('error', function (error) {
      console.error('错误: ', error)
    })
    serialPort.on('close', () => {
      serialPort = null
    })
  })
}

function close() {
  if (serialPort && serialPort.isOpen) {
    serialPort.close()
  }
}

export default {
  open,
  close,
  cmdList,
  sendData
}
